package com.hs.app.action.data;
 
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.hs.app.model.CdcFileinfo;
import com.hs.app.service.IDataService;
import com.hs.auth.model.HsAccount;
import com.hs.core.action.BaseAction;
import com.hs.core.cache.GlobalParamCache;
import com.hs.core.db.DBMgr;
import com.hs.core.utils.PageParam;
import com.hs.core.utils.PageUtil;
import com.hs.core.utils.SystemUtil;
import com.hs.core.utils.TimeUtil;
import com.hs.core.utils.Tools;
@Controller   
public class OldDataController  extends BaseAction {
    /**
	 * 
	 */
	private static final Logger logger = Logger.getLogger(OldDataController.class);
	private IDataService dataService;
	@Autowired  
	public void setDataService(IDataService dataService) {
		this.dataService = dataService;
	}
	/**
	  * 标准数据导入
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	 * @throws Exception 
	  */
	 @RequestMapping(value="/data/old/pdfupload.do")   
    public void pdfupload(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws Exception {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;   
		 MultipartFile multipartFile = multipartRequest.getFile("pdffile");  
 		 String paperid = request.getParameter("paperid");
		 logger.debug("paperid:" + paperid);
		 logger.debug("String paperid = multipartRequest" +   multipartRequest.getParameter("paperid"));
		 String fileName = multipartFile.getOriginalFilename(); 
		// String webRoot = SystemUtil.getWebappRoot().toString();
		// webRoot = webRoot.replace("\\", "/") + "/temp"; 
		 String sep = System.getProperty("file.separator");
		 sep = "/"; 
//		 File rootDir = new File(webRoot); 
//		 if (!rootDir.exists()) {
//			rootDir.mkdirs(); 
//		 }
		 String sql = "update SCHD_OLDPAPER set ISIMG=1 where id=?";
		 //查询该文献是否已经上传原文
		 this.getDbo(request).update(sql, new Object[]{paperid});
		 logger.debug("1");
		 HsAccount acc = this.getCurrentuser(request);
		 String username = acc==null?"":acc.getUserinfo()==null?"":acc.getUserinfo().getUsername();
		 String[] bookinfo = this.writePdfFile(multipartFile.getBytes(), fileName);
		 CdcFileinfo pdffile = new CdcFileinfo();
		 pdffile.setPapercontent(new String(multipartFile.getBytes()));
		 pdffile.setPaperid(new Long(paperid));
		 pdffile.setProdate(TimeUtil.getCurrentDate());
		 logger.debug("2");
		 pdffile.setProuser(username);
		 //pdffile.setProversion(1l);
		 pdffile.setPapertitle(fileName);
		 pdffile.setSavepath(bookinfo[0]+bookinfo[1]);
		 this.dataService.saveObject(pdffile);
		 logger.debug("3");
//		 File file = new File(webRoot + sep + fileName);
//		 BufferedOutputStream bf = new BufferedOutputStream(new FileOutputStream(file));
//		 bf.write(multipartFile.getBytes());
//		 bf.close();
		 logger.debug("文件"+fileName+"上传成功!");
		 
		 response.getWriter().write("文件"+fileName+"上传成功!");
	 }
	 private String[] writePdfFile(byte[] fileContent,String fileName) throws Exception{
			String[] temp = new String[3];
			StringBuffer buffer = new StringBuffer();
			String sep = System.getProperty("file.separator");
			sep = "/"; 
			//存储路径
			String webRoot = GlobalParamCache.getInst().getParamByKey("filepath");// SystemUtil.getWebappRoot().getPath() + sep +  "upload";//SWFConvertUtil.getParamMap("filepath");// 
//			if(null != filesavepath)
//				webRoot = filesavepath;
			String middlePath = Tools.buildFileSubdirectory();
			String fileSaveUUID = com.hs.core.utils.UUIDGenerator.getUUID();
			String fullPath = webRoot + sep + middlePath;
			buffer.append(middlePath).append(sep);
			 
			logger.debug("fullPath:" + fullPath);
			File rootDir = new File(webRoot); 
			File directory = null;
			if (!rootDir.exists()) {
				rootDir.mkdirs(); 
			} 
			directory = new File(rootDir, middlePath);
			if(!directory.exists() && !directory.mkdirs()){
				logger.error("创建文件存储路径失败【" + directory.getAbsolutePath() + "】");
			}  
			 
			StringBuffer fileLocation = new StringBuffer(webRoot);
			StringBuffer fileFullPath = new StringBuffer();
			fileLocation.append(middlePath); 
			fileLocation.append(sep); 
			
			fileFullPath.append(middlePath); 
			fileFullPath.append(sep); 
			String fileSaveName = "";
			int pos = fileName.lastIndexOf('.');
			if (pos == -1) {
				fileSaveName = fileSaveUUID;
			} else {
				fileSaveName = fileSaveUUID + fileName.substring(pos);
			}
			//buffer.append(fileSaveName);
			temp[2] = fileLocation.toString();
			fileLocation.append(fileSaveName);
			fileFullPath.append(fileSaveName);
			 
			logger.info("to store file: " + fileLocation);
			File file = new File(fileLocation.toString());
			if(!file.exists()){
				file.createNewFile();
			}
			logger.info("file created!");
			BufferedOutputStream bf = new BufferedOutputStream(
					new FileOutputStream(file));
			bf.write(fileContent);
			bf.close();
			temp[0] = buffer.toString();
			temp[1] = fileSaveName;
			return temp;
		}

	 @RequestMapping("/data/old/downloadFile.do")   
		public   ModelAndView  downloadFile(HttpServletRequest request,
				HttpServletResponse response, ModelAndView mv) throws Exception {
				Map modelMap = new HashMap();
				String pid = request.getParameter("pid");
			    
			    DBMgr dbo = DBMgr.getDbUtilInst(request.getSession().getServletContext());
			    List datalist = dbo.queryList("select PAPERTITLE,SAVEPATH from SCHD_FILEINFO where id=(select max(id) from SCHD_FILEINFO where PAPERID=?)", new Object[]{pid});
			    //ChdFileinfo pobj = (ChdFileinfo)dataService.findByID(ChdFileinfo.class, new Long(pid));
				String filePath = GlobalParamCache.getInst().getParamByKey("filepath");
				if(datalist.size()>0){
					Map filedata = (Map)datalist.get(0);
					String fileName = (String)filedata.get("PAPERTITLE");
					String ext = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
		 			logger.debug("ext:" + ext);
	
		 			String fileDbURL = (String)filedata.get("SAVEPATH");
		 			logger.debug("fileDbURL:" + fileDbURL);
		 			filePath += fileDbURL;
					logger.debug("test文件是否存在:" + new File(filePath).exists());
	
		 			filePath = filePath.replace("\\", "/");
		 			logger.debug("fileurl:" + filePath); 
					File file = new File(filePath);
					logger.debug("文件是否存在:" + file.exists());
			       
			        int fileLength = (int)file.length();
			        try{
			        	int                 length   = 0;
				        ServletOutputStream op       = response.getOutputStream();
				        ServletContext      context  = request.getSession().getServletContext();
				        String              mimetype = context.getMimeType( fileName );
				        byte[]   byteContents   =   new   byte[fileLength];   
				        FileInputStream fis   =   new   FileInputStream(file);   
				        int   retcd   =   fis.read(byteContents);   
				        fis.close();    
				        logger.debug("mimetype:" + mimetype);
				        response.setContentType(mimetype == null?"application/pdf":mimetype );
				        response.setContentLength( retcd );
				        response.setHeader( "Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes("gb2312"),"ISO-8859-1") + "\"" );
	
				        op.write(byteContents,0,retcd); 
				        op.close();
			            }catch(Exception e){
			            	e.printStackTrace();
			            }
	             }
	            return null;
		}
	
	 /**
	  * 古籍文献数据列表
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/data/old/booklistframe.do", method = RequestMethod.GET)   
     public ModelAndView booklistframe(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		   	
		  return new ModelAndView("app/data/old/booklistframe",modelMap);
		 
	 }
	 /**
	  * 古籍文献数据列表
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/data/old/olddatalist.do")   
     public ModelAndView bookList(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 PageParam pageParam = new  PageParam(request,"data/old/olddatalist.do");
		 PageUtil pageUtil = null;
		 String orderName = request.getParameter("orderName");
		 String orderNum = request.getParameter("orderNum"); 
		 StringBuffer orderByStr = new StringBuffer(" order by ");
		 if(StringUtils.isNotBlank(orderName)){
		    	if("1".equals(orderNum)){
		    		orderByStr.append(orderName).append(" asc");
		    	}
		    	if("2".equals(orderNum)){
		    		orderByStr.append(orderName).append(" desc");
		    	}
		    }else{
		    	orderByStr.append("a.bookname").append(" asc");
		    	orderName = "a.bookname";
		    	orderNum = "2";
		    }
		 request.setAttribute("orderName", orderName); 
		 request.setAttribute("orderNum", orderNum); 
		 pageParam.getConditionMap().put("orderName", orderName);
		 pageParam.getConditionMap().put("orderNum", orderNum);
		 StringBuffer searchBuffer = new StringBuffer(" select a from SchdOldpaper a where 1=1   ");
			String bookname = request.getParameter("bookname");  
			String tcmname = request.getParameter("tcmname");  
			String booktext = request.getParameter("booktext"); 

			//String periodicalname = request.getParameter("periodicalname"); 
			request.setAttribute("bookname", bookname==null?"":bookname.trim());
			request.setAttribute("tcmname", tcmname==null?"":tcmname.trim());
			request.setAttribute("booktext", booktext==null?"":booktext.trim());
			//request.setAttribute("periodicalname", periodicalname);
			if(StringUtils.isNotBlank(bookname)){
				String temp = bookname.trim();
				searchBuffer.append(" and a.bookname like '%").append(temp).append("%' ");
				pageParam.getConditionMap().put("bookname", temp==null?"":temp); 
				pageParam.getConditionMap().put("title", temp==null?"":temp); 
			}  
			if(StringUtils.isNotBlank(tcmname)){
				pageParam.getConditionMap().put("tcmname", tcmname==null?"":tcmname.trim());
				searchBuffer.append(" and (a.tcmname like '%"+tcmname.trim()+"%') "); 
			}
			if(StringUtils.isNotBlank(booktext)){
				pageParam.getConditionMap().put("booktext", booktext==null?"":booktext.trim());
				searchBuffer.append(" and (a.originaltext like '%"+booktext.trim()+"%') "); 
			}
//			 
			
			
			searchBuffer.append(orderByStr);
			logger.debug("sql:"+searchBuffer);
			//Map data = new HashMap();
			pageParam.setSearchSql(searchBuffer.toString());
			pageUtil = dataService.getPageList(pageParam);
			modelMap.put("dataList", pageUtil);     
		  return new ModelAndView("app/data/old/olddatalist",modelMap);
		 
	 } 
	 
	 /**
	  * 古籍文献页面
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/data/old/bookimportview.do", method = RequestMethod.GET)   
     public ModelAndView bookimportview(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		   	
		  return new ModelAndView("app/data/old/bookimportview",modelMap);
		 
	 }
	 
	 
	 
 
	public String getCell(HSSFCell cell){
		if(cell==null)return "";
		switch(cell.getCellType()){
			case HSSFCell.CELL_TYPE_NUMERIC:
				return (long)cell.getNumericCellValue() + "";
			case HSSFCell.CELL_TYPE_STRING:
				return cell.getStringCellValue();
			case HSSFCell.CELL_TYPE_FORMULA:
				return cell.getCellFormula();
			case HSSFCell.CELL_TYPE_BLANK:
				return "";
			case	HSSFCell.CELL_TYPE_BOOLEAN:
				return cell.getBooleanCellValue() + "";
			case HSSFCell.CELL_TYPE_ERROR:
	    	    return cell.getErrorCellValue() + "";
	    	default:
	    		return "";
		}
	} 
	 /**
	  * 书籍题录信息导出
	  * @param request
	  * @param response
	  * @return
	 * @throws Exception 
	  */
	@RequestMapping("/data/old/exportBookData.do")   
	public ModelAndView exportBookData(HttpServletRequest request,
			HttpServletResponse response) throws Exception { 
		try  {
			String ids = request.getParameter("ids");
			if(StringUtils.isEmpty(ids)){
				return null;
			}else{
				ids = ids.substring(0,ids.length()-1);
			}
			String path = this.exportBookData(ids);
			System.out.println("message::" + path );
			//  path是指欲下载的文件的路径。 
			//response.setCharacterEncoding("UTF-8");
			File file  =   new  File(path);
			String filename  =  file.getName();
			int fileLength = (int)file.length();
			int                 length   = 0;
	        ServletOutputStream op       = response.getOutputStream();
	        ServletContext      context  = request.getSession().getServletContext();
	        String              mimetype = context.getMimeType( filename );
	        byte[]   byteContents   =   new   byte[fileLength];   
	        FileInputStream fis   =   new   FileInputStream(file);   
	        int   retcd   =   fis.read(byteContents);   
	        fis.close();    
	        logger.debug("mimetype:" + mimetype);
	        response.setContentType(mimetype == null?"application/vnd.ms-excel":mimetype );
	        response.setContentLength( retcd );
	        response.setHeader( "Content-Disposition", "attachment; filename=\"" + new String(filename.getBytes("gb2312"),"ISO-8859-1") + "\"" );
	        op.write(byteContents,0,retcd); 
	        op.close();
    }  catch  (IOException ex) {
        ex.printStackTrace();
    }
		return null;  
	} 
	
	/**
	 * 生成古书籍题录文件
	 * @return 生成的文件的路径
	 */
	public String exportBookData(String rids){
		String message = "false";
		 try {
				HSSFWorkbook wb = new HSSFWorkbook(); 
				 HSSFSheet sheet = wb.createSheet("new sheet"); 
				 HSSFRow row = sheet.createRow((short)0); 
				 row.createCell(0).setCellValue("条目编码");
				 row.createCell(1).setCellValue("书籍名称");
				 row.createCell(2).setCellValue("中医病名");
				 row.createCell(3).setCellValue("原文文本化");
				 row.createCell(4).setCellValue("卷册章节");
				 row.createCell(5).setCellValue("版本");
				 row.createCell(6).setCellValue("录入人");
				 row.createCell(7).setCellValue("录入日期");
				 row.createCell(8).setCellValue("朝代"); 
				 row.createCell(9).setCellValue("病名"); 
				 CellStyle cs=wb.createCellStyle(); 
				 List  accList = DBMgr.getDbUtilInst().queryList("select * from SEARCHMVIEW where id in("+rids+") order by id",null);
				 
				 
				 for(int i=0; i<accList.size(); i++){
						Map data = (Map)accList.get(i);
						HSSFRow onerow = sheet.createRow((short)(i+1)); 
						
						 onerow.createCell(0).setCellValue(String.valueOf(data.get("ID"))); 
						 onerow.createCell(1).setCellValue((String)data.get("PERIODICALNAME")); 
						 onerow.createCell(2).setCellValue((String)data.get("TCMNAME")); 
						 onerow.createCell(3).setCellValue((String)data.get("ABSTRACT")); 
						 onerow.createCell(4).setCellValue((String)data.get("VOLUMESECTION")); 
						 onerow.createCell(5).setCellValue((String)data.get("BOOKVERSION")); 
						 onerow.createCell(6).setCellValue((String)data.get("INPUTUSER")); 
						 onerow.createCell(7).setCellValue((String)data.get("INPUTDATE")); 
						 onerow.createCell(8).setCellValue((String)data.get("BOOKCD"));  
						 onerow.createCell(9).setCellValue((String)data.get("DISNAME"));  
 				 }	
				 String tempFilepath = SystemUtil.getWebappRoot().toString();
				 tempFilepath = tempFilepath.replace("\\", "/") + "/temp";
				 System.out.println("tempFilepath::" + tempFilepath );
				 File tempfile = new File(tempFilepath);
				 if(!tempfile.exists()){
					 tempfile.mkdirs();
				 }
				 String destfile = tempFilepath + "/" + "古籍数据.xls";
				 FileOutputStream fileOut = new FileOutputStream(destfile); 
				 wb.write(fileOut); 
				 fileOut.close();
				 message = destfile;
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		return message;
		
	}
 
}
